package com.adtec.yxdemo.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.adtec.yxdemo.mockLogin.entity.po.YxAccountInfo;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;


public class LoginUtil {
    // 单例实例
    public static final LoginUtil me = new LoginUtil();
    // 日志对象
    public static final Log log = Log.getLog(LoginUtil.class);


    /**
     * 密码登录
     *
     * @param account
     * @return
     */
    public static boolean loginByPwd(YxAccountInfo account) {
        HttpRequest.closeCookie();
        String logDesc = account.getAccountUsername() + "密码登录";
        String url = "http://trade.zgyxcgw.cn:8000/com.hsnn.sso/login.html";
        HttpRequest request = HttpUtil.createGet(url).removeHeader("User-Agent").addHeaders(getHeaders(account));
        HttpResponse response = YxUtil.excute(request, logDesc + 1, false);
        account.setCookie(YxUtil.getCookie(response));

        url = "http://trade.zgyxcgw.cn:8000/com.hsnn.sso/captchaImg";
        request = HttpUtil.createGet(url).removeHeader("User-Agent").addHeaders(getHeaders(account));
        response = YxUtil.excute(request, logDesc + 2, false);
        if (response == null || response.getStatus() != 200) {
            log.warn(logDesc + "2失败响应:" + response);
            return false;
        }
        String code = YxUtil.getCodeByImg(response.bodyBytes(), "1003");
        if (StrKit.isBlank(code)) {
            log.warn(logDesc + "2失败，识别验证码失败");
            return false;
        }

        url = "http://trade.zgyxcgw.cn:8000/com.hsnn.sso/loginAuth.html";
        String body = "username=%s&password=%s&answer=%s";
        body = String.format(body, Base64.encode(account.getAccountUsername()), Base64.encode(account.getAccountPassword()), code);
        request = HttpUtil.createPost(url).removeHeader("User-Agent").addHeaders(getHeaders(account)).body(body);
        response = YxUtil.excute(request, logDesc + 3, false);
        account.setNum(response.getStatus());
        if (response == null || response.getStatus() != 302) {
            if (response != null && response.getStatus() == 200) {
                String errMsg = StringUtils.substringBetween(response.body(), "<div class='regBar errorTips fa fa-minus-circle'>", "</div>");
                log.warn(logDesc + "3失败:" + errMsg);
                System.out.println(errMsg);
                account.setRemarks(errMsg);
            } else {
                log.warn(logDesc + "3失败响应:" + response);
            }
            return false;
        }

        account.setCookie(YxUtil.combCookie(response, account.getCookie()));
        url = response.header("Location");
        request = HttpUtil.createGet(url).removeHeader("User-Agent").addHeaders(getHeaders(account));
        response = YxUtil.excute(request, logDesc + 4, false);
        url = "http://trade.zgyxcgw.cn:8081/index.html";
        request = HttpUtil.createGet(url).removeHeader("User-Agent").addHeaders(getHeaders(account));
        response = YxUtil.excute(request, logDesc + 5, false);
        account.setCookie(YxUtil.combCookie(response, account.getCookie()));

        log.info(logDesc + "成功，cookie：" + account.getCookie());
        return true;
    }

    /**
     * 获取请求头信息
     *
     * @param yxAccountInfo
     * @return
     */
    private static Map<String, String> getHeaders(YxAccountInfo yxAccountInfo) {
        HttpRequest.closeCookie();
        Map<String, String> headers = new HashMap<>();
        if (yxAccountInfo != null && StrKit.notBlank(yxAccountInfo.getCookie())) {
            headers.put("Cookie", yxAccountInfo.getCookie());
        }
        String cookie = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36";
        headers.put("User-Agent", cookie);
        return headers;
    }

}

